package cn.tinlan.shopcoin.app.car;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.CallBackProxy;
import com.zhouyou.http.callback.CallClazzProxy;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.subsciber.BaseSubscriber;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.tinlan.shopcoin.R;
import cn.tinlan.shopcoin.Utils.ConvertUtil;
import cn.tinlan.shopcoin.Utils.SPUtils;
import cn.tinlan.shopcoin.Utils.ToastUtils;
import cn.tinlan.shopcoin.app.car.adapter.ShopCarRVAdapter;
import cn.tinlan.shopcoin.app.car.model.ShopCarItemModel;
import cn.tinlan.shopcoin.app.car.model.ShoppingCarItemModel;
import cn.tinlan.shopcoin.app.mine.order.OrderDetailActivity;
import cn.tinlan.shopcoin.base.BaseActivity;
import cn.tinlan.shopcoin.base.CustomApiResult;
import cn.tinlan.shopcoin.widget.category.Constants;
import io.reactivex.Observable;

/**
 * Created by Mortimer on 2018/12/26. 13:50
 * 佛祖🙏，永无bug。
 */
public class CarActivity extends BaseActivity {

    @BindView(R.id.shop_car_titlebar)
    TitleBar titleBar;
    @BindView(R.id.shop_car_rv)
    RecyclerView shop_car_rv;
    @BindView(R.id.shop_car_empty)
    View emptyView;
    @BindView(R.id.car_goshopping_tv)
    TextView goShoppingTV;
    @BindView(R.id.tv_shopcart_totalprice)
    TextView totalPrice;
    @BindView(R.id.tv_shopcart_totalnum)
    TextView totalNum;


    //private static  boolean isEdit = false;
    private ShopCarRVAdapter shopCarRVAdapter;
    private List<ShopCarItemModel> shopCarList;

    private List<ShopCarItemModel.ShopCarItemBean> selectCarIdList;

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_car;
    }

    @Override
    public void initView() {
        super.initView();

        drawableDefaultBar();

        initMTitleBView();
        initRView();
        initEmptyView();
    }

    @Override
    public void initData() {
        super.initData();

        shopCarList = new ArrayList<>();

        loadShoppingCarData();
    }

    private void initMTitleBView(){
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                finish();
            }

            @Override
            public void onTitleClick(View v) {

            }

            @Override
            public void onRightClick(View v) {
                deleteGood();
            }
        });
    }

    private void initRView() {
        if (shopCarRVAdapter == null){
            LinearLayoutManager llm = new LinearLayoutManager(CarActivity.this, LinearLayoutManager.VERTICAL, false);
            shop_car_rv.setLayoutManager(llm);
//            shop_car_rv.addItemDecoration(new DividerItemDecoration(mActivity, DividerItemDecoration.VERTICAL));
            shopCarRVAdapter = new ShopCarRVAdapter(R.layout.view_shopcar_item, R.layout.view_shopcar_head, null);
            shop_car_rv.setAdapter(shopCarRVAdapter);
        }else {
            shopCarRVAdapter.notifyDataSetChanged();
        }

        shopCarRVAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(new Intent(CarActivity.this, OrderDetailActivity.class));
            }
        });

        shopCarRVAdapter.setOnmShopHeadClickListener(new ShopCarRVAdapter.OnShopHeadClickListener() {
            @Override
            public void onShopHeadClick(View view, String shopid) {

            }

            @Override
            public void onShopItemClick(ShopCarItemModel.ShopCarItemBean item, int position) {
                ShopCarItemModel tempModel = shopCarList.get(position);
                if (tempModel.getItemModel().isSelected()) {

                    tempModel.getItemModel().setSelected(false);
                }else {

                    tempModel.getItemModel().setSelected(true);
                }

                if (selectCarIdList == null) {
                    selectCarIdList = new ArrayList<>();

                    selectCarIdList.add(item);
                }else {
                    if (selectCarIdList.contains(item)) {

                        selectCarIdList.remove(item);
                    }else {

                        selectCarIdList.add(item);
//                        for (int i = 0; i< selectCarIdList.size();i++) {
//                            ShopCarItemModel.ShopCarItemBean tempModel = selectCarIdList.get(i);
//                            if (tempModel.getId() == item.getId()) {
//
//                            }
//
//                        }
                    }

                }


                float totalMoney = 0;
                for (int i=0;i<selectCarIdList.size();i++) {
                    ShopCarItemModel.ShopCarItemBean selectItem = selectCarIdList.get(i);
                    totalMoney += ConvertUtil.convertToFloat(selectItem.getPrice(),0);
                }
                totalPrice.setText("总价：¥"+Float.toString(totalMoney));
                totalNum.setText("共"+Integer.toString(selectCarIdList.size())+"件商品");
            }
        });
    }

    private void initEmptyView() {
        goShoppingTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadShoppingCarData();
            }
        });
    }

    //加载购物车
    private void loadShoppingCarData() {
        Observable<List<ShoppingCarItemModel>> observable = EasyHttp.get(Constants.ShoppingCar)
                .params("user_id", SPUtils.getUserID(CarActivity.this))
                .execute(new CallClazzProxy<CustomApiResult<List<ShoppingCarItemModel>>, List<ShoppingCarItemModel>>(new TypeToken<List<ShoppingCarItemModel>>() {}.getType()) {
                });

        observable.subscribe(new BaseSubscriber<List<ShoppingCarItemModel>>() {
            @Override
            public void onError(ApiException e) {
                if (emptyView.getVisibility() == View.GONE) {
                    emptyView.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onNext(List<ShoppingCarItemModel> list) {
                List<ShoppingCarItemModel> tempList = list;
                String tempShopID = "";
                if (shopCarList.size() > 0){
                    shopCarList.clear();
                }
                for (int i = 0; i<tempList.size();i++) {

                    if (!tempShopID.equals(tempList.get(i).getShop_id())){
                        shopCarList.add(new ShopCarItemModel(true, tempList.get(i).getShop_name(),tempList.get(i).getShop_id()));
                        tempShopID = tempList.get(i).getShop_id();
                        Log.d("tempShopId",tempShopID+i);
                        if (i != 0 ) {//&& i != 1
                            ShopCarItemModel tempModel = shopCarList.get(i-1);
                            ShopCarItemModel.ShopCarItemBean itemBean = tempModel.itemModel;
                            if (itemBean != null) {
                                tempModel.t.setIslastgood(true);
                            }

                        }
                    }

                    boolean tempIsLastItem = false;
                    if (i == tempList.size() - 1){
                        tempIsLastItem = true;
                    }
                    shopCarList.add(new ShopCarItemModel(new ShopCarItemModel.ShopCarItemBean(tempList.get(i),"",tempIsLastItem)));
                }

                if (shopCarList.size() > 0){

                    if (emptyView.getVisibility() == View.VISIBLE) {
                        emptyView.setVisibility(View.GONE);
                    }
                    shopCarRVAdapter.setNewData(shopCarList);
                }

            }
        });
    }




    private void deleteGood() {

        if (selectCarIdList.size() < 1) {
            ToastUtils.show("您还没有选择商品");
            return;
        };

        StringBuilder sb = new StringBuilder();
        for (int i=0;i<selectCarIdList.size();i++) {
            sb.append(selectCarIdList.get(i).getId());
            if (i != selectCarIdList.size() - 1) {
                sb.append(",");
            }
        }
        String ids = sb.toString();
        EasyHttp.post(Constants.DeleteGoodsFromCar)
                .params("ids",ids)
                .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {

//                        ToastUtils.show("删除失败");
                    }

                    @Override
                    public void onSuccess(String s) {

                        ToastUtils.show("删除成功");
                    }
                }) {
                });
    }
}
